package com.xyxy.platform.modules.core.utils.converter;

import java.util.Map;
import java.util.TreeMap;

/**
 * 基础类型的转换器工厂, int, long, float, double, date
 * Created by juju on 14-5-15.
 */
public class PrimitiveTransformerFactory {

    private static Map<String, StringTransformer> transformerMap = null;

    private static void initialize() {
        StringTransformer transformer = new IntegerTransformer();
        transformerMap.put(transformer.getClazz().getSimpleName(), transformer);
        transformer = new LongTransformer();
        transformerMap.put(transformer.getClazz().getSimpleName(), transformer);
        transformer = new FloatTransformer();
        transformerMap.put(transformer.getClazz().getSimpleName(), transformer);
        transformer = new DoubleTransformer();
        transformerMap.put(transformer.getClazz().getSimpleName(), transformer);
        transformer = new DateTransformer();
        transformerMap.put(transformer.getClazz().getSimpleName(), transformer);
        transformer = new NumberTransformer();
        transformerMap.put(transformer.getClazz().getSimpleName(), transformer);
        transformer = new StringStringTransformer();
        transformerMap.put(transformer.getClazz().getSimpleName(), transformer);
    }

    public static <T> StringTransformer<T> getStringTransformer(Class<T> clazz) {
        if (null == clazz) {
            throw new IllegalArgumentException("转换器类不能为空");
        }
        String simpleName = clazz.getSimpleName();
        if (null == transformerMap) {
            synchronized (PrimitiveTransformerFactory.class) {
                if (null == transformerMap) {
                    transformerMap = new TreeMap<>();
                    initialize();
                }
            }
        }
        if (transformerMap.containsKey(simpleName)) {
            return transformerMap.get(simpleName);
        }
        throw new UnsupportedOperationException("当前转换器不被支持:" + clazz.getSimpleName());
    }

    public static <T> T transformFromStr(String from, Class<T> type) {
        StringTransformer<T> transformer =
                PrimitiveTransformerFactory.getStringTransformer(type);
        return transformer.transform(from);
    }

}
